package com.wq.jdk8;

import java.lang.ref.WeakReference;

/**
 * @Author: wangqiang20995
 * @Date:2019/6/20
 * @Description:
 * @Resource:
 */
public class WeakReferenceDemo {
    public static void main(String[] args) {
        Apple apple = new Apple("hello");

        WeakHolder weakHolder = new WeakHolder(apple);
        //new Apple出来的相当于局部变量，除了被WeakHolder持有，不会被其他持有，所以当发生gc的时候，这个变量就会被回收
        WeakHolder temp = new WeakHolder(new Apple("temp"));

        System.out.println("apple==null:" + (weakHolder.get() == null));
        System.out.println("temp==null:" + (temp.get() == null));
        System.gc();

        Apple holder = weakHolder.get();
        System.out.println("holder==null:" + (holder == null));
        System.out.println("apple==null:" + (apple == null));
        System.out.println("holder==apple:" + (holder == apple));

        Apple tempHolder = temp.get();
        System.out.println(tempHolder == null);
    }
}

/**
 * 弱引用对象，当发生gc时，不管对空间是否充足，只要被该弱引用指向的对象（也就是泛型T）没有其他地方使用它
 * 那么泛型T的实例对象就会被GC
 */
class WeakHolder extends WeakReference<Apple> {
    public WeakHolder(Apple referent) {
        super(referent);
    }
}

/**
 * WeakReference指向的对象，成为被弱引用对象引用的对象
 */
class Apple {
    private String name;

    public Apple(String name) {
        this.name = name;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println(name + "--finalize");
    }

    @Override
    public String toString() {
        return "Apple{" +
                "name='" + name + '\'' +
                '}';
    }
}
